//
//  SetSafetyTimeViewController.m
//  IntelligentHousehold
//
//  Created by wmwMAC on 17/6/27.
//  Copyright © 2017年 Cassie. All rights reserved.
//

#import "SetSafetyTimeViewController.h"

#import <MessageUI/MessageUI.h>//系统短信


#define titleBtn_height 30
#define titleTF_height 50

@interface SetSafetyTimeViewController ()<UITextFieldDelegate,MFMessageComposeViewControllerDelegate>
{
    
    
    BOOL OpenOrClose;
    
    NSString *msgTitle;//发送短信内容
}

@property (nonatomic, strong) UITextField *tf;
@end

@implementation SetSafetyTimeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = BaseColor;
    
    self.navigationItem.title = @"设置安全检测时间";
    
    CGFloat btn_Weidth = [BasePublicClass weidthWithLabelText:@" 设置安全检测时间(单位:小时)" labelHeight:20 labelFont:13];
    UIButton *titleBtn = [MyUtil createBtnFrame:CGRectMake(10, 0, btn_Weidth +30, titleBtn_height) title:@" 设置安全检测时间(单位:小时)" bgImage:@"" selectBgImage:nil image:@"gth" target:self action:nil];
    [titleBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
    [titleBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self.view addSubview:titleBtn];
    
    _tf = [MyUtil createTextFiledFrame:CGRectMake(0, titleBtn_height, kUIScreenWidth, titleTF_height) placeHolder:@"请输入检测时间"];
    _tf.keyboardType = UIKeyboardTypeNumberPad;
    _tf.delegate = self;
    [self.view addSubview:_tf];
    
    UIButton *openBtn = [MyUtil createBtnFrame:CGRectMake(10, titleTF_height+titleBtn_height+50, kUIScreenWidth-20, titleTF_height-10) title:@"开启安全检测" bgImage:@"ann" selectBgImage:nil image:nil target:self action:nil];
    [openBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [openBtn addTarget:self action:@selector(openBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:openBtn];
    
    UIButton *closeBtn = [MyUtil createBtnFrame:CGRectMake(10, CGRectGetMaxY(openBtn.frame)+10, kUIScreenWidth-20, titleTF_height-10) title:@"关闭安全检测" bgImage:@"" selectBgImage:nil image:nil target:self action:nil];
    closeBtn.backgroundColor = [UIColor whiteColor];
    [closeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(closeBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:closeBtn];
    
    //
    [self ChangeSecurity];
    
}

-(void)openBtnAction{
    //    timeStr = _tf.text;
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSString *lockNumberStr = saveDic[@"locknumber"];
    
    if ([NSString stringWithFormat:@"%@",_tf.text].length == 0 || _tf.text.integerValue == 0) {
        [MBProgressHUD showText:@"请填写检测时间"];
    }else if (!lockNumberStr.length){
        [MBProgressHUD showText:@"请设置门锁号码"];
    }else{
        
        OpenOrClose = 1;//开启检测
        msgTitle = [NSString stringWithFormat:@"setsafetime:%@",_tf.text];
        [self sendMsg];
        
    }
    
    
    
}
-(void)closeBtnAction{
    
    OpenOrClose = 0;//关闭检测
    msgTitle = @"clearsafetime";
    [self sendMsg];
}
//发送短信


//修改安全检测时间
-(void)GetSecurity{
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    
    
    NSString *url = [NSString stringWithFormat:SECURITY,RealmName];
    NSMutableDictionary *parameDic = [NSMutableDictionary dictionary];
    [parameDic setObject:[NSString stringWithFormat:@"%d",OpenOrClose] forKey:@"type"];
    [parameDic setObject:saveDic[@"user_id"] forKey:@"user_id"];
    [parameDic setObject:[NSString stringWithFormat:@"%@",_tf.text] forKey:@"detetime"];
    [parameDic setObject:saveDic[@"token"] forKey:@"token"];
    [parameDic setObject:saveDic[@"locknumber"] forKey:@"locknumber"];

    
    
    
    if (OpenOrClose) {
        [parameDic setObject:@"setsafetime:4" forKey:@"command"];//clearsafetime
    }else{
        [parameDic setObject:@"clearsafetime" forKey:@"command"];
    }
    
    
   
        [HttpRequest postWithURLString:url parameters:parameDic success:^(id responseObject) {
            
            if (OpenOrClose && [[responseObject objectForKey:@"msg"] isEqualToString:@"success"]) {
                [MBProgressHUD showText:@"成功开启"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [MBProgressHUD hideHUD];
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    
                });
                
            }else if (!OpenOrClose && [[responseObject objectForKey:@"msg"] isEqualToString:@"success"]){
                [MBProgressHUD showText:@"成功关闭"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [MBProgressHUD hideHUD];
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    
                });
                
            }else{
                [MBProgressHUD showText:[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"msg"]]];
            }
            
        } failure:^(NSError *error) {
            
        }];
    
    
    
    
    
    
}


//获取安全检测时间
-(void)ChangeSecurity{
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    
    NSString *url = [NSString stringWithFormat:SECURIGYS,RealmName];
    NSMutableDictionary *parameDic = [NSMutableDictionary dictionary];
    [parameDic setObject:saveDic[@"token"] forKey:@"token"];
    [parameDic setObject:saveDic[@"user_id"] forKey:@"user_id"];
    [parameDic setObject:saveDic[@"locknumber"] forKey:@"locknumber"];

    
    [HttpRequest postWithURLString:url parameters:parameDic success:^(id responseObject) {
        
        NSDictionary *dataDic = [responseObject objectForKey:@"data"];
        NSString *detetimeStr = [dataDic objectForKey:@"detetime"];
        
        if (detetimeStr.length) {
            NSString *typeStr = [dataDic objectForKey:@"type"];
            if (typeStr.integerValue == 0) {
                _tf.placeholder = @"请输入安全检测时间(安全监测已关闭)";
            }else if (typeStr.integerValue == 1){
                _tf.text = [NSString stringWithFormat:@"%@",detetimeStr];
            }
            
        }else{
            if ([[responseObject objectForKey:@"ret"] integerValue]==1) {
                [MBProgressHUD showText:[responseObject objectForKey:@"msg"]];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [MBProgressHUD hideHUD];
                    
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
        }
        
        /*{
         msg = "token\U4e0d\U5339\U914d";
         ret = 1;
         }*/
    } failure:^(NSError *error) {
        
    }];
    
}


#pragma mark -------------- 发送短信 ----------------
-(void)sendMsg{
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSString *telStr = saveDic[@"locknumber"];
//    telStr = @"10086";

    if (telStr.length>4) {
        [self showMessageView:[NSArray arrayWithObjects:telStr, nil] title:nil body:msgTitle];

    }else{
        [MBProgressHUD showText:@"请先设置门锁号码"];
    }
    
}
-(void)showMessageView:(NSArray *)phones title:(NSString *)title body:(NSString *)body
{
    if([MFMessageComposeViewController canSendText] )
    {
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc] init];
        controller.recipients = phones;
        controller.navigationBar.tintColor = [UIColor redColor];
        controller.body = body;
        controller.messageComposeDelegate = self;
        [self presentViewController:controller animated:YES completion:nil];
        
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"该设备不支持短信功能 " delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}
#pragma mark - MFMessageComposeViewController

-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    if (result) {
        if (MessageComposeResultSent) {//短信发送成功
            
            [self GetSecurity];
        }else{
            
            
        }
    }
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
